package com.itheima.canal.listener;

import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZJ
 */
@CanalEventListener
public class SpuListener {

    //监控 goods 中的spu表
    //监控上架
    //改变了发送supid到mq 中
    @Autowired
    RabbitTemplate rabbitTemplate;
    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodsUp(CanalEntry.EventType eventType,CanalEntry.RowData rowData){
        //改变前的值  放入map
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        Map<String , String> oldMap = new HashMap();
        beforeColumnsList.forEach((c)->oldMap.put(c.getName(),c.getValue()));
        //改变后的值  放入map
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        Map<String , String> newMap = new HashMap();
        afterColumnsList.forEach((c)->newMap.put(c.getName(),c.getValue()));
        if (oldMap.get("is_marketable").equals("0")&&"1".equals(newMap.get("is_marketable"))){
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newMap.get("id"));
        }
    }
    @ListenPoint(schema = "changgou_goods",table = "tb_spu")
    public void goodsDEL(CanalEntry.EventType eventType,CanalEntry.RowData rowData){
        //改变前的值  放入map
        List<CanalEntry.Column> beforeColumnsList = rowData.getBeforeColumnsList();
        Map<String , String> oldMap = new HashMap();
        beforeColumnsList.forEach((c)->oldMap.put(c.getName(),c.getValue()));
        //改变后的值  放入map
        List<CanalEntry.Column> afterColumnsList = rowData.getAfterColumnsList();
        Map<String , String> newMap = new HashMap();
        afterColumnsList.forEach((c)->newMap.put(c.getName(),c.getValue()));
        if (oldMap.get("is_marketable").equals("1")&&"0".equals(newMap.get("is_marketable"))){
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DEL_EXCHANGE,"",newMap.get("id"));
        }
        //获取最新审核通过商品 status 0->1
        //商品只要是正常在卖   商品信息一边动就往mq中发消息
        if("0".equals(oldMap.get("status"))&&"1".equals(newMap.get("status"))){
            //发送spuId到mq
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE, "", newMap.get("id"));
        }
    }

}
